<?php

namespace app\api\model;

use app\admin\model\product\Product;
use app\common\model\User;
use extend\Poster as PosterExtend;
use think\Model;
require_once ROOT_PATH.'extend/Poster.php';

/**
 * 配置清单
 */
class Diy extends Model
{

    // 表名
    protected $name = 'diy';
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = '';
    // 追加属性
    protected $append = [
        'createtime_text'
    ];

    public function getCreatetimeTextAttr($value, $data)
    {
        $value = $value ? $value : ($data['createtime'] ?? "");
        return is_numeric($value) ? date("Y-m-d H:i", $value) : $value;
    }


    public function add($params)
    {
        $diy_title = isset($params['title']) ? $params['title'] : '';
        $cpu = isset($params['cpu']) ? $params['cpu'] : [];
        $jixiang = isset($params['jixiang']) ? $params['jixiang'] : [];
        $neicun = isset($params['neicun']) ? $params['neicun'] : [];
        $peijian = isset($params['peijian']) ? $params['peijian'] : [];
        $sanre = isset($params['sanre']) ? $params['sanre'] : [];
        $waishe = isset($params['waishe']) ? $params['waishe'] : [];
        $xianka = isset($params['xianka']) ? $params['xianka'] : [];
        $xianshiqi = isset($params['xianshiqi']) ? $params['xianshiqi'] : [];
        $yingpan = isset($params['yingpan']) ? $params['yingpan'] : [];
        $zhuban = isset($params['zhuban']) ? $params['zhuban'] : [];
        $dianyuan = isset($params['dianyuan']) ? $params['dianyuan'] : [];
        $user_id = $params['user_id'];
        $id = isset($params['id']) ? $params['id'] : 0;

        if (empty($cpu)||empty($jixiang)||empty($neicun)||empty($sanre)||empty($xianka)||empty($yingpan)||empty($zhuban)||empty($dianyuan)){
            throw new \Exception('配置未完成');
        }
        //dump($cpu);
        $content = [];
        $title = $cpu['title'];
        $all_prices = 0;

        $all_prices+=$cpu['price'];
        array_push($content,['goods_id'=>$cpu['id'],'price'=>$cpu['price']]);
        /*foreach ($cpu as $k=>$v){
            dump($v);die;
            $title = $v['title'];
            $all_prices+=$v['price'];
            array_push($content,['goods_id'=>$v['id'],'price'=>$v['price']]);
        }*/
        $all_prices+=$jixiang['price'];
        array_push($content,['goods_id'=>$jixiang['id'],'price'=>$jixiang['price']]);
        /*foreach ($jixiang as $k=>$v){
            $all_prices+=$v['price'];
            array_push($content,['goods_id'=>$v['id'],'price'=>$v['price']]);
        }*/
        foreach ($neicun as $k=>$v){
            $all_prices+=$v['price'];
            array_push($content,['goods_id'=>$v['id'],'price'=>$v['price']]);
        }
        foreach ($peijian as $k=>$v){
            $all_prices+=$v['price'];
            array_push($content,['goods_id'=>$v['id'],'price'=>$v['price']]);
        }
        $all_prices+=$sanre['price'];
        array_push($content,['goods_id'=>$sanre['id'],'price'=>$sanre['price']]);
        /*foreach ($sanre as $k=>$v){
            $all_prices+=$v['price'];
            array_push($content,['goods_id'=>$v['id'],'price'=>$v['price']]);
        }*/
        foreach ($waishe as $k=>$v){
            $all_prices+=$v['price'];
            array_push($content,['goods_id'=>$v['id'],'price'=>$v['price']]);
        }
        foreach ($xianka as $k=>$v){
            $all_prices+=$v['price'];
            array_push($content,['goods_id'=>$v['id'],'price'=>$v['price']]);
        }
        foreach ($xianshiqi as $k=>$v){
            $all_prices+=$v['price'];
            array_push($content,['goods_id'=>$v['id'],'price'=>$v['price']]);
        }
        foreach ($yingpan as $k=>$v){
            $all_prices+=$v['price'];
            array_push($content,['goods_id'=>$v['id'],'price'=>$v['price']]);
        }
        $all_prices+=$zhuban['price'];
        array_push($content,['goods_id'=>$zhuban['id'],'price'=>$zhuban['price']]);
        /*foreach ($zhuban as $k=>$v){
            $all_prices+=$v['price'];
            array_push($content,['goods_id'=>$v['id'],'price'=>$v['price']]);
        }*/
        $all_prices+=$dianyuan['price'];
        array_push($content,['goods_id'=>$dianyuan['id'],'price'=>$dianyuan['price']]);
        /*foreach ($dianyuan as $k=>$v){
            $all_prices+=$v['price'];
            array_push($content,['goods_id'=>$v['id'],'price'=>$v['price']]);
        }*/
        $content = json_encode($content,320);
        $model = new Diy();

        $data  = [
            'user_id'=>$user_id,
            'content'=>$content,
            'title'=>$diy_title?$diy_title:$title,
            'all_prices'=>$all_prices,
            'detail'=>json_encode(input(),320)
        ];
        if ($id){
            $res = $model->save($data,['id'=>$id]);
        } else {
            $res = $model->save($data);
        }


        return $res;
    }


    public function getLists($params)
    {
        $user_id = $params['user_id'];

        $lists = Diy::where(['user_id'=>$user_id])
            ->order('createtime desc')
            ->paginate(10, false, ['query' => request()->get()]);
        foreach ($lists as $k=>$v){
            $ginfo = [];
            $content = json_decode($v['content'],true);
            //dump($content);die;
            foreach ($content as $kk=>$vv){
                $product = Product::get($vv['goods_id']);
                array_push($ginfo,$product);
            }

            $lists[$k]['ginfo'] = $ginfo;
        }
        return $lists;
    }


    public function check_jrx($params)
    {
        $cpu = isset($params['cpu']) ? $params['cpu'] : [];//
        $jixiang = isset($params['jixiang']) ? $params['jixiang'] : [];//
        $neicun = isset($params['neicun']) ? $params['neicun'] : [];//
        $sanre = isset($params['sanre']) ? $params['sanre'] : [];//
        $xianka = isset($params['xianka']) ? $params['xianka'] : [];//
        $yingpan = isset($params['yingpan']) ? $params['yingpan'] : [];//
        $zhuban = isset($params['zhuban']) ? $params['zhuban'] : [];//
        $dianyuan = isset($params['dianyuan']) ? $params['dianyuan'] : [];//
        $gonghao = $params['gonghao'];

        $dianyuan_data = [];
        $jixiang_data = [];
        $neicun_data_list = [];
        $sanre_data = [];
        $xianka_data_list = [];
        $yingpan_data = [];
        $zhuban_data = [];

        if ($dianyuan){
            if ($gonghao-150>$dianyuan){
                $dianyuan_msg = "电源满足硬件功耗所需，当前总功耗【'{$gonghao}'W】，电源功率【{$dianyuan['dygl']}W】";
                $dianyuan_type = 'success';
            } elseif($gonghao>$dianyuan) {
                $dianyuan_msg = "电源功率不足，当前总功耗【{$gonghao}W】，电源功率【{$dianyuan['dygl']}W】";
                $dianyuan_type = 'error';
            } else {
                $suggest = $dianyuan['dygl']+150;
                $dianyuan_msg = "电源功率可能不足，当前总功耗【{$gonghao}W】，电源功率【{$dianyuan['dygl']}W】，建议电源【{$suggest}W】";
                $dianyuan_type = 'warn';
            }
            $dianyuan_data = [
                'msg'=>$dianyuan_msg,
                'type'=>$dianyuan_type
            ];
        }

        if ($jixiang){
            $zhuban_arr = explode(',',$jixiang['zhuban']);
            if (in_array($zhuban['banxing'],$zhuban_arr)){
                $jixiang_data = [
                    'type'=>'success',
                    'msg'=>"机箱与主板大小匹配，机箱是【{$jixiang['zhuban']}】，主板是【{$zhuban['banxing']}】"
                ];
            } else {
                $jixiang_data = [
                    'type'=>'error',
                    'msg'=>"机箱与主板大小不匹配，机箱是【{$jixiang['zhuban']}】，主板是【{$zhuban['banxing']}】"
                ];
            }
            $shuileng_arr = explode(',',$jixiang['shuileng']);
            if (in_array($sanre['leixing'],$shuileng_arr)){
                $sanre_data = [
                    'type'=>'success',
                    'msg'=>"水冷散热器与机箱兼容，水冷类型【{$sanre['leixing']}】，机箱支持水冷类型【{$jixiang['shuileng']}】"
                ];
            } else {
                $chicun = $sanre['chicun'];

                $sanre_data = [
                    'type'=>'success',
                    'msg'=>"已选散热器的尺寸高度【{$chicun}】，机箱对CPU散热器的限高要求【{$jixiang['cpu']}】"
                ];
            }
        }

        if ($zhuban&&$cpu){
            if ($zhuban['jiekou']==$cpu['jiekou']){
                $zhuban_data = [
                    'type'=>'success',
                    'msg'=>"CPU和主板接口兼容【{$zhuban['jiekou']}】"
                ];
            } else {
                $zhuban_data = [
                    'type'=>'error',
                    'msg'=>"CPU和主板接口不兼容，CPU【{$cpu['jiekou']}】，主板【{$zhuban['jiekou']}}】"
                ];
            }
        }

        if ($zhuban&&$yingpan){
            $yingpan_count = count($yingpan);
            $yingpan_data = [
                'type'=>'success',
                'msg'=>"主板m2接口共【{$zhuban['m2']}个】，m2硬盘共【{$yingpan_count}个】"
            ];
        }

        if ($xianka&&$jixiang){
            $xianka_data_list = [];
            foreach ($xianka as $k=>$v){
                $rank = $k+1;
                $xianka_data = [
                    'type'=>'success',
                    'msg'=>"已选显卡{$rank}的长度【{$v['length']}】，机箱对显卡限长要求【{$jixiang['xianka']}】"
                ];
                array_push($xianka_data_list,$xianka_data);
            }
        }

        if ($neicun){
            $neicun_data_list = [];
            $neicun_count = count($neicun);
            $total_ddrrl = 0;
            foreach ($neicun as $k=>$v){

                preg_match('/\d+/', $v['rongliang'], $match);
                $total_ddrrl+=$match[0];

                $rank = $k+1;
                if ($v['daishu']==$zhuban['jiekou']){
                    $neicun_data_1 = [
                        'type'=>'success',
                        'msg'=>"主板和内存'{$rank}'接口兼容，接口【'{$v['daishu']}'】"
                    ];
                } else {
                    $neicun_data_1 = [
                        'type'=>'error',
                        'msg'=>"主板和内存'{$rank}'接口不兼容，内存接口【'{$v['daishu']}'】，主板接口【'{$zhuban['jiekou']}'】"
                    ];
                }
                array_push($neicun_data_list,$neicun_data_1);
            }

            $neicun_data_2 = [
                'type'=>'success',
                'msg'=>"已选【'{$neicun_count}'个】内存，主板内存插槽数量为【'{$zhuban['ddrcc']}'个】"
            ];
            array_push($neicun_data_list,$neicun_data_2);

            $neicun_data_3 = [
                'type'=>'success',
                'msg'=>"已选内存总容量【'{$total_ddrrl}'GB】，主板DDR最大容量为【'{$zhuban['ddrrl']}'】"
            ];
            array_push($neicun_data_list,$neicun_data_3);
        }


        $data = [
            'dianyuan'=>$dianyuan_data,
            'jixiang'=>$jixiang_data,
            'neicun_list'=>$neicun_data_list,
            'sanre'=>$sanre_data,
            'xianka_list'=>$xianka_data_list,
            'yingpan'=>$yingpan_data,
            'zhuban'=>$zhuban_data,

        ];

        return $data;
    }


    //海报
    public function poster($page,$qrcode_param,$app_type)
    {
        //$qrcode_info = $this->getQrcode($app_type, $page, $qrcode_param);

        //if ($qrcode_info[ 'code' ] < 0) throw new \Exception($qrcode_info['msg']);

        $member_info = User::get($qrcode_param[ 'suid' ]);
        if (empty($member_info))throw new \Exception('未获取到会员信息');

        $diy_info = Diy::get($qrcode_param[ 'diy_id' ]);
        if (empty($diy_info))throw new \Exception('未获取到配置信息');
        $content = json_decode($diy_info->content,true);
        $goods_id = array_column($content,'goods_id');
        $product_list = collection(\app\api\model\product\Product::where('id','in',$goods_id)
            ->field('id,deploy_type,title,image,price')->select())->toArray();

        try {

            $poster = new PosterExtend(740, 1100);
            $option = [
                [
                    'action' => 'setBackground', // 背景色
                    'data' => [255, 255, 255]
                ],
                [
                    'action' => 'imageCopy', // 写入店铺图片
                    'data' => [
                        ROOT_PATH.'public/assets/img/bg.png',
                        5,
                        5,
                        730,
                        1000,
                        10
                    ]
                ],
                /*[
                    'action' => 'imageCopy', // 写入二维码
                    'data' => [
                        $qrcode_info[ 'data' ][ 'path' ],
                        505,
                        880,
                        205,
                        205
                    ]
                ],*/

            ];
            //dump($product_list);die;
            foreach ($product_list as $k=>$v){

                $deploy_type_name = '';
                $type =  [
                    'action' => 'imageText', // 写入商品类型
                    'data' => [
                        $deploy_type_name,
                        25,
                        [ 0, 0, 0 ],
                        40,
                        300+$k*20,
                        440,
                        1,
                        true
                    ]
                ];
                array_push($option,$type);
                $img =  [
                    'action' => 'imageCopy', // 写入商品图片
                    'data' => [
                        $v['image'],
                        40,
                        300+$k*20,
                        40,
                        40,
                        10
                    ]
                ];
                array_push($option,$img);
                $product =  [
                    'action' => 'imageText', // 写入商品名称
                    'data' => [
                        $v['title'],
                        25,
                        [ 0, 0, 0 ],
                        40,
                        300+$k*20,
                        440,
                        1,
                        true
                    ]
                ];
                array_push($option,$product);
                $price =  [
                    'action' => 'imageText', // 写入商品价格
                    'data' => [
                        $v['price'],
                        25,
                        [ 0, 0, 0 ],
                        40,
                        300+$k*20,
                        440,
                        1,
                        true
                    ]
                ];
                array_push($option,$price);
            }
            $option_res = $poster->create($option);
            if (is_array($option_res)) return $option_res;

            $res = $option_res->jpeg('upload/poster', 'diy' . $qrcode_param[ 'suid' ] . '_' . $app_type);

            if ($res['code']==0){
                return $res['data']['path'];
            } else {
                throw new \Exception($res['message']);
            }
            //return $res;

        }  catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * 获取二维码
     * @param unknown $app_type 请求类型
     * @param unknown $page uniapp页面路径
     * @param unknown $qrcode_param 二维码携带参数
     * @param string $promotion_type 活动类型 null为无活动
     */
    private function getQrcode($app_type, $page, $qrcode_param)
    {
        $data = [
            'app_type' => $app_type,
            'type' => 'get',
            'data' => $qrcode_param,
            'page' => $page,
            'qrcode_path' => 'upload/qrcode/share',
            'qrcode_name' => 'share' . '_' . $qrcode_param[ 'suid' ],
        ];
        $qrcode_model = new Qrcode();

        if ($app_type=='weapp'){
            $res = $qrcode_model->createWxQrcode($data);
        } else {
            $res = $qrcode_model->createQrcode($data);
        }

        return $res;
    }
}
